<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>账号管理</title>
  <!-- import CSS -->
  <link rel="shortcut icon" href="../favicon.ico">
  <link rel="stylesheet" href="../plugins/ElementUI/index-2.3.9.css">
  <link href="../css/common.css" rel="stylesheet">
  <!-- import Vue before Element -->
  <script src="../plugins/ElementUI/vue-2.5.16.js"></script>
  <script src="../plugins/ElementUI/index-2.3.9.js"></script>
  <script src="../plugins/ElementUI/vue-resource.min.js"></script>
  <style>
    .icoColor{
      color:#18A689
    }
    .lushu-box-text{
      background-color: #f5f5f5;
      height: 30px;
      font-size: 14px;
      color: #999;
      line-height: 30px;
      border-radius: 4px;
      padding: 0px 10px;
      margin: 6px 6px 6px 0;
      cursor: pointer;
    } 
  </style>
</head>
<body>
  <div id="app" v-cloak v-show="addShow" class="animated fadeInRight">
    <el-form :model="form" label-width="80px" style="width: 900px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="用户名">
            <el-input v-model="form.nickName" clearable size="small"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="角色">
            <el-select v-model="form.role" placeholder="请选择" clearable size="small" style="width: 100%">
              <el-option
                v-for="item in options"
                :key="item.role"
                :label="item.roleName"
                :value="item.role">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电子邮箱">
            <el-input v-model="form.email" clearable size="small" type="email" @blur="checkEmail"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="选择时间">
            <el-date-picker
              v-model="form.datePicker"
              type="daterange"
              align="right"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否激活">
            <el-radio-group v-model="form.inUse">
              <el-radio :label="-1">全部</el-radio>
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" size="small" @click="onSubmit" v-show="resourceMap.queryUserInfo">&nbsp;&nbsp;查询&nbsp;&nbsp;</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <el-button type="primary" size="small" icon="el-icon-circle-plus" @click="NewAdd" v-show="resourceMap.saveUserInfo">新增</el-button>
      <el-button type="primary" size="small" icon="el-icon-delete" @click="onSelectDel" v-show="resourceMap.deleteUserInfo">删除选中</el-button>
      <el-button type="primary" size="small" icon="el-icon-setting" @click="onCheckSet" v-show="resourceMap.batchUpdateUserInfo">设置选中</el-button>
    </div>
    <br>
    <el-table :data="tableData.list" border :max-height="windowHeight" size="small" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" ></el-table-column>
      <el-table-column prop="nickName" label="用户名" width=""></el-table-column>
      <el-table-column prop="role" label="角色"> </el-table-column>
      <el-table-column prop="departmentName" label="所属组织"> </el-table-column>
      <el-table-column prop="inUse" label="是否激活"> 
        <template slot-scope="scope">
          <span>{{scope.row.inUse?'是':'否'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="gmt_modified" sortable label="修改时间" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index,scope.row)" v-show="resourceMap.updateUserInfo">编辑</el-button>
          <el-button size="mini" type="info" @click="handleInfo(scope.$index,scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-sizes="[20,50,100,150,200]"
      :page-size="pageSize"
      layout="sizes, prev, pager, next"
      :total="tableData.totalElement">
    </el-pagination>
    <!-- dialog NewAdd -->
    <el-dialog title="用户管理" :visible.sync="dialogNewAdd" :before-close="beforeClose" :close-on-click-modal="false" width="40%">
      <el-form :model="formDialogAdd" :rules="rules" ref="ruleForm">
        <el-row>
          <el-col :xs="24" :sm="18" :lg="12">
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="nickName">
              <el-input v-model="formDialogAdd.nickName"  placeholder="请输入用户名" clearable size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="18" :lg="12">
            <el-form-item label="角色" :label-width="formLabelWidth" prop="role">
              <el-select v-model="formDialogAdd.role" placeholder="请选择" size="small" style="width:100%">
                  <el-option
                    v-for="item in options"
                    :key="item.role"
                    :label="item.roleName"
                    :value="item.role">
                  </el-option>
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="18" :lg="12">
            <el-form-item label="电子邮箱" size="small" :label-width="formLabelWidth" prop="email">
              <el-input v-model="formDialogAdd.email" placeholder="请输入邮箱" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="18" :lg="12">
            <el-form-item label="登录密码" size="small" :label-width="formLabelWidth" prop="password">
              <el-input v-model="formDialogAdd.password" placeholder="请输入密码" :type="switchPass?'test':'password'" style="width:100%">
                <i slot="suffix" class="el-input__icon el-icon-view" :class="{icoColor:switchPass}" @click="switchPassworld"></i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="18" :lg="12">
            <el-form-item label="绑定组织" :label-width="formLabelWidth">
              <div class="lushu-box-text" @click="departmentFocus">{{formDialogAdd.departmentName}}</div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="18" :lg="12">
            <el-form-item label="是否激活" :label-width="formLabelWidth">
              <el-radio-group v-model="formDialogAdd.inUse">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="beforeClose" size="small">取 消</el-button>
        <el-button type="primary" @click="newAddSubmit('ruleForm')" size="small">确 定</el-button>
      </div>
    </el-dialog>
    <!-- dialog Select -->
    <el-dialog title="设置选中" :visible.sync="dialogSelect" width="35%">
      <el-form :model="formDialogSelect" style="text-align: center;">
        <el-form-item label="" prop="role">
          <label>角色：</label>
          <el-select v-model="formDialogSelect.role" clearable size="small" placeholder="请选择">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="售后" value="servicer"></el-option>
          </el-select>
          <el-button type="primary" size="small" @click="selectRole">确 定</el-button>
        </el-form-item>
        <el-form-item label="">
          <label>激活：</label>
          <el-radio-group v-model="formDialogSelect.activation" style="width: 217px">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
          <el-button type="primary" size="small" @click="selectInuse">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- dialog Information -->
    <el-dialog title="详细信息" :visible.sync="dialogInfo">
      <el-form :model="formDialogInfo" class="el-table-expand el-form--inline">
        <el-form-item label="用户名">
          <span>{{ formDialogInfo.nickName }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <span>{{ formDialogInfo.role }}</span>
        </el-form-item>
        <el-form-item label="登录密码">
          <span>{{ formDialogInfo.password }}</span>
        </el-form-item>
        <el-form-item label="邮箱">
          <span>{{ formDialogInfo.email }}</span>
        </el-form-item>
        <el-form-item label="是否激活">
          <span>{{ formDialogInfo.inUse?'是':'否'}}</span>
        </el-form-item>
        <el-form-item label="修改时间">
          <span>{{ formDialogInfo.gmt_modified }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- dialog department -->
    <el-dialog title="选择组织" :visible.sync="dialogDepartment" width="30%">
        <el-tree
          :props="defaultProps"
          :data="departmentList"
          node-key="id"
          ref="tree"
          @node-click="handleNodeClick"
          default-expand-all
          :expand-on-click-node="false">
          <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>              
          </span>
      </el-tree>
    </el-dialog>
  </div>
</body>
  <script src="../plugins/Underscore/underscore-min.js"></script>
  <script src="../js/ApiRequest.js"></script>
  <script>
    var vm = new Vue({
      el: '#app',
      data: function() {
        var checkName = function(rule, value, callback){
          if (!value) {
            return callback(new Error('用户名不能为空'));
          }
          setTimeout(function(){
            var test = RE.reName(value);
            if(!test){
              callback(new Error('4到16位（字母，数字，下划线）且连续重复不能超过三个'));
            }else{
              callback();
            }
          }, 500);
        };
        return { 
          addShow:false,
          resourceMap:storageLocal.getName('user'),
          pickerOptions: {
            shortcuts: [{
              text: '最近一周',
              onClick:function(picker) {
                var end = new Date();
                var start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近一个月',
              onClick:function(picker) {
                var end = new Date();
                var start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近三个月',
              onClick:function(picker) {
                var end = new Date();
                var start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }]
          },
          tableData: [],
          form: {
              nickName: '',
              email:'',
              role: '',
              inUse:-1,
              datePicker:''
          },
          options:[],
          dialogNewAdd: false,
          formDialogAdd: {
            inUse:1
          },
          dialogSelect: false,
          formDialogSelect: {
            role: '',
            activation:0,
          },
          formLabelWidth: '120px',
          windowHeight: (window.innerHeight||(document.documentElement&&document.documentElement.clientHeight)||document.body.clientHeight) - 270,
          multipleSelection:[],
          dialogInfo:false,
          formDialogInfo: {},
          switchPass:false,//密码时候明文
          currentPage:1,
          pageSize:50,
          rules:{
            nickName:[{ required: true,validator:checkName, trigger: 'blur' }],
            role:[{ required: true, message: '请选择角色', trigger: 'change' }],
            email:[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ],
            password:[{ required: true, message: '请填写登录密码', trigger: 'blur' }]
          },
          dialogDepartment:false,
          defaultProps:{
              children: 'childDepartment',
              label: 'departmentName',
              isLeaf:'lastLeaf',
              type:'departmentType'
          },
          departmentList:[{ //组织架构数据
              departmentName: '上海同捷',
              departmentType:1,
              id: 0,
              childDepartment:[]
          }]
        }
      },
      mounted:function(){
        this.$nextTick(function(){
          this.requestModel()
          this.getSelectRole()
        })
      },
      updated:function(){
        this.addShow = true
      },
      methods: {
          NewAdd:function(){
            this.formDialogAdd = {
                inUse:1
            };
            this.dialogNewAdd = true
          },
          onSubmit:function() {//查询提交
            vm.currentPage = 1;
            vm.requestModel();
          },
          handleSelectionChange:function(val){
            this.multipleSelection = val;
          },
          switchPassworld:function(){
            this.switchPass = !this.switchPass
          },
          newAddSubmit:function(formName){//新增用户,更新用户
            this.$refs[formName].validate(function(valid){
              if(vm.formDialogAdd.departmentName == undefined && vm.formDialogAdd.departmentId == undefined) {
                vm.$message.warning('请绑定组织！')
                return false;
              }
              if (valid) {
                var data = {
                  id: vm.formDialogAdd.id?vm.formDialogAdd.id:'',
                  nickName: vm.formDialogAdd.nickName,
                  password:vm.formDialogAdd.password,
                  role:vm.formDialogAdd.role,
                  email:vm.formDialogAdd.email,
                  inUse:vm.formDialogAdd.inUse,
                  departmentId:vm.formDialogAdd.departmentId
                }
                resourceRequst("/user/saveUserInfo",data,function(res){
                    vm.dialogNewAdd = false;
                    if(data.id != ''){
                      vm.$message({
                        message: '修改成功',
                        type: 'success'
                      });
                      vm.requestModel()
                    }else{
                      vm.tableData.list.unshift(res.getResult);
                      vm.$message({
                        message: '添加成功',
                        type: 'success'
                      });
                    }
                })
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          onSelectDel:function() {//删除操作
            if(this.multipleSelection.length == 0){
              this.$message({ showClose: true, message: '提示，还未选中对象', type: 'warning', duration:1500 });
              return
            }
            var arry = _.map(vm.multipleSelection, function(num){ 
              return num.id; 
            });
            this.$alert('此操作将删除选中数据, 是否继续?', '提示', {
              confirmButtonText: '确定',
              showCancelButton:true,
              type: 'warning',
              callback: function(action){
                if (action == "confirm") {
                  var data = {allKeys:arry}
                  resourceRequst("/user/deleteUserInfo",data,function(res){
                    var table = _.filter(vm.tableData.list, function(item){ 
                      return arry.indexOf(item.id) < 0 
                    });
                    vm.tableData.list = table;
                    vm.$message({ type: 'success', message: "删除成功！" });
                  })
                }
              }
            });
          },
          onCheckSet:function() {
            if(this.multipleSelection.length == 0){
              this.$message({
                showClose: true,
                message: '提示，还未选中对象',
                type: 'warning',
                duration:1000
              });
              return
            }
            this.dialogSelect=true            
          },
          selectRole:function(){
            var arry = _.map(vm.multipleSelection, function(num){ 
              return num.id; 
            });
            var data = {
              allKeys:arry,
              role: this.formDialogSelect.role
            }
            if (data.role == '') {
              this.$message('请选择角色！');
              return
            }
            resourceRequst("/user/batchUpdateUserInfo",data,function(res){
              console.log(res)
              vm.dialogSelect = false
              vm.requestModel();
            })
          },
          selectInuse:function(){
            var arry = _.map(vm.multipleSelection, function(num){ 
              return num.id; 
            });
            var data = {
              allKeys:arry,
              inUse: this.formDialogSelect.activation
            }
            resourceRequst("/user/batchUpdateUserInfo",data,function(res){
                console.log(res)
                vm.dialogSelect = false
                vm.requestModel();
            })
          },
          handleEdit:function(index, row) {//编辑
            row.index = index;
            cookieUtil.setCookie('active_account',row,1)
            this.formDialogAdd = row;
            this.dialogNewAdd = true;
          },
          beforeClose:function(){
            var data = cookieUtil.getCookie('active_account')
            if(data){
              vm.tableData.list.splice(data.index,1,data)
              this.dialogNewAdd = false;
              cookieUtil.removeCookie('active_account')
            }else{
              this.dialogNewAdd = false;
            }
            this.$refs.ruleForm.resetFields();
          },
          handleInfo:function(index, row) {//详情
            this.dialogInfo = true
            this.formDialogInfo = row
          },
          handleSizeChange:function(val) {
           this.pageSize = val;
           this.requestModel()
          },
          handleCurrentChange:function(val) {
            this.requestModel()
          },
          checkEmail:function(e){
            var data = e.target.value;
            var test = RE.reEmail(data);
            if(!test){
              this.$message({
                type:"warning",
                message:"请正确填写邮箱！！",
                duration:1500
              })
            }
          },
          getSelectRole:function(){//获取角色下拉列表 && 组织下拉列表
            getSelectRole(function(res){
              vm.options = res.getResult
            });
            resourceRequst("/department/queryDepartmentTreeList",{id:0},function(res){
              vm.departmentList[0].childDepartment = res.resultList
            },true)
          },
          //绑定组织点击事件
          departmentFocus:function(){
            this.dialogDepartment = true
          },
          handleNodeClick(item) {            
            this.formDialogAdd.departmentName = item.departmentName;
            this.formDialogAdd.departmentId = item.id;

            this.dialogDepartment = false
          },
          requestModel:function(){
            var inUse;
            if(this.form.inUse == -1){inUse = ""}else{inUse = this.form.inUse}
            if(RE.reEmail(this.form.email) || this.form.email==""){
              var data = {
                "startTime":this.form.datePicker?this.form.datePicker[0]:'',
                "endTime":this.form.datePicker?this.form.datePicker[1]:'',
                "nickName":this.form.nickName?this.form.nickName:'', 
                "email":RE.reEmail(this.form.email)?this.form.email:'', 
                "role":this.form.role?this.form.role:'', 
                "inUse":inUse, 
                "page":this.currentPage -1 ?this.currentPage -1 :'',
                "pageSize":this.pageSize?this.pageSize:''
              }
              resourceRequst("/user/queryUserInfo",data,function(res){
                  vm.tableData = res.getResult
              })
            }else{
              this.$message({
                message: '请正确填写邮箱！！',
                type: 'warning',
                duration:1000
              });
            }
          }
      }
    })
  </script>
</html>